package com.neucloud.da.edgeside.model.handle;

import com.alibaba.fastjson.JSONObject;
import com.neucloud.da.edgeside.model.constant.Result;
import com.neucloud.da.edgeside.model.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;

import java.io.IOException;
import java.util.Scanner;

@Slf4j
public class CustomRestTemplateHandler extends DefaultResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
        if(clientHttpResponse.getStatusCode() != HttpStatus.OK && clientHttpResponse.getStatusCode() != HttpStatus.CREATED){
            return true;
        }
        return false;
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        String erroMessage = "网络异常，请稍后再试";
        try {
            Scanner scanner = new Scanner(response.getBody()).useDelimiter("\\A");
            String body = scanner.hasNext() ? scanner.next() : "";
            try{
                Result result = JSONObject.parseObject(body, Result.class);
                erroMessage = result.getMessage();
                if (null == erroMessage) {
                    JSONObject parse = (JSONObject) JSONObject.parse(body);
                    if(parse.containsKey("message")){
                        erroMessage = parse.getString("message");
                    }
                    if(parse.containsKey("error_message")){
                        erroMessage = parse.getString("error_message");
                    }
                }
            }catch (Exception e){
                if(body.indexOf("@type")>=0){
                    body = body.replace("@type", "type");
                }

                try{
                    JSONObject parse = (JSONObject) JSONObject.parse(body);
                    if(parse.containsKey("message")){
                        erroMessage = parse.getString("message");
                    }
                    if(parse.containsKey("error_message")){
                        erroMessage = parse.getString("error_message");
                    }

                } catch (Exception err){
                    erroMessage = body;
                }
            }
            log.error("error result:{}", JSONObject.toJSONString(response));
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            throw new BusinessException(erroMessage);
        }
    }

}
